﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Grishko.UI;
using System.Web.UI.WebControls;
using OutdoorLib.BaseEntity.Dictionary;
using Grishko.DataTier;
using System.Text;
using System.IO;

namespace Grishko.UI
{
    public class TreePostBackControlNew : TreeControl
    {
        //Операции 0- выбрать 1-добавить 2-удалить
        
        private const string EventArgPref = "_EventArg";
        private const string SelectNodePref = "_SelectNodePref";
                
        public Unit _AddDelWidtch                      = new Unit("50px");
        private string _CssNode                     = "TreeNode";
        private string _CssSelectedNode             = "SelectedNode";        
        private string SubmitCommandFormat          = "TreeItemSubmit('{0}','{1}', '{2}', '{3}')";


        //выделить 
        public Func<string, bool> OnSelectedNodeChanged;
        //Добавить ноду
        public Func<string, bool> OnAddNode;
        //Удалить ноду
        public Func<string, bool> OnRemoveNode;


        /// <summary>
        /// Нода CSS
        /// </summary>
        public string CssNode { get { return _CssNode; } set { _CssNode = value; } }
        
        /// <summary>
        /// Выделенная нода CSS
        /// </summary>
        public string CssSelectedNode { get { return _CssSelectedNode; } set { _CssSelectedNode = value; } }

        //Id  скрытого поля - хранилище событийного ID
        public string hf_EventArgID { get { return this.ID + EventArgPref; } }


        //Id  скрытого поля - хранилище SelectedNode
        protected string hf_SelectNodeID { get { return this.ID + SelectNodePref; } }

        protected override void OnBefore_RenderControl(ref Panel Root)
        {
            ///Формируем хранилища для выбранных нод, ид папки справочника , ид типа справочника
            HiddenField hfEvent = new HiddenField() { ID = hf_EventArgID, Value = "" };
            Root.Controls.Add(hfEvent);

            HiddenField hf = new HiddenField() { ID = hf_SelectNodeID, Value = SelectedNodeID };
            Root.Controls.Add(hf);

        }

        public string SelectedNodeID 
        { 
            get;
            set; 
        }

        

        protected override void OnLoad(EventArgs e)
        {

            if (this.DesignMode)
                return;

            SelectedNodeID = HttpContext.Current.Request.Form[hf_SelectNodeID];

            //Есть элемент событие в ViewState?
            object ev = HttpContext.Current.Request.Form[hf_EventArgID];
            if (null == ev || string .IsNullOrEmpty (ev.ToString ()))
                return;

            object id =HttpContext.Current.Request.Form[hf_SelectNodeID];
            
            

            int ev_i=Convert .ToInt16(ev) ;
            string id_s= id.ToString();
            switch (ev_i)
            { 
                case 0:
                    if (null != OnSelectedNodeChanged)
                        OnSelectedNodeChanged(id_s); 
                    break;
                case 1:
                    if (null != OnAddNode)
                        OnAddNode(id_s); 
                    break;
                case 2:
                    if (null != OnRemoveNode)
                        OnRemoveNode(id_s);
                    break;
            }

            base.OnLoad(e);
        }

        protected override System.Web.UI.Control F_BuildNode(TreeEntitySingle nd)
        {
            System.Web.UI.Control res = null;
            Func<string ,string[] , LinkButton> fGetBtn=delegate (string Text,string [] arg )
            {
                LinkButton result = new LinkButton() { ID = Guid.NewGuid().ToString(), Text = Text };                
                result.Font.Size = new FontUnit(FontSize.Small);
                result.ForeColor = System.Drawing.ColorTranslator.FromHtml("Red");
                result.Style.Add("display", "none");
                result.OnClientClick = string.Format(SubmitCommandFormat, arg);
                return result;
            };

            //зовем внешнего прорисовщика
            res = Call_BuildNodeEvent(this, nd);
            if (null != res)
                return res;


            Table tbl = new Table() { CellPadding = 0, CellSpacing = 1 };            
            TableRow rw = new TableRow();            
            TableCell cl = new TableCell();

            ///Сама ветка
            LinkButton btn = new LinkButton();            
            btn.Text = (nd as DictionaryItem).Value.ToString();            
            cl.Controls.Add(btn);
            btn.Font.Bold =nd.ID.Equals (SelectedNodeID);

            string[] arr_sel = { hf_SelectNodeID, nd.ID, hf_EventArgID, 0.ToString() };
            btn.OnClientClick = string.Format(SubmitCommandFormat, arr_sel);


            rw.Cells.Add(cl);
            

            //ячейки - добавить запись
            string s_AddBtnID = string.Empty;
            cl = new TableCell() { HorizontalAlign = HorizontalAlign.Right, Width = _AddDelWidtch };
            string[] arr1= { hf_SelectNodeID, nd.ID, hf_EventArgID, 1.ToString() };
            btn = fGetBtn("доб.", arr1);            
            s_AddBtnID = btn.ClientID;
            cl.Controls.Add(btn);
            rw.Cells.Add(cl);


            string s_DelBtnID = string.Empty;
            if (nd.ChildNodes.Count == 0)
            {
                cl = new TableCell() { Width =_AddDelWidtch };
                string[] arr2 = { hf_SelectNodeID, nd.ID, hf_EventArgID, 2.ToString() };
                btn = fGetBtn("удал.", arr2);            
                s_DelBtnID=btn.ClientID ;                                
                cl.Controls.Add(btn);
                rw.Cells.Add(cl);
                
            }

            string[] param = new string []{s_AddBtnID ,s_DelBtnID};
            rw.Attributes.Add("onmouseover", string.Format ("TreeItemOnMouseOver('{0}','{1}');",param));
            rw.Attributes.Add("onmouseout", string.Format("TreeItemOnMouseOut('{0}','{1}');", param));
            rw.Style.Add("cursor", "pointer"); 

            tbl.Rows.Add(rw);
            
            return tbl;


        }
        
        public TreePostBackControlNew()
        {
         
        }

    }
}
